package org.hiucung.hlsdownloader.ui.screens

import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.shuyu.gsyvideoplayer.GSYVideoManager
import org.hiucung.hlsdownloader.ui.components.GSYVideoPlayer

/**
 * @title: VideoPlayerScreen
 * @projectName HLS Downloader
 * @description: 视频播放页面
 * @author Kicc
 * @date 2025/9/4 0:23
 */
@Composable
fun VideoPlayerScreen(videoPath: String) {
    val lifecycleOwner = LocalLifecycleOwner.current
    val context = LocalContext.current
    val activity = context as? ComponentActivity

    Box(modifier = Modifier.fillMaxSize()) {
        GSYVideoPlayer(
            modifier = Modifier
                .fillMaxSize()
                .height(240.dp), // 可以控制高度，宽度通常由父布局决定
            videoUrl = videoPath,
            videoTitle = videoPath,
            isPlaying = true,
            onBackPressed = {
                // 这里可以处理全屏状态下的返回逻辑，例如改变状态
                // 全屏状态下，GSYVideoPlayer 自己会处理视图变化，这里主要是通知Compose可能的状态变化
                activity?.finish()
            }
        )
    }

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_PAUSE -> {
                    GSYVideoManager.onPause() // 全局暂停
                }
                Lifecycle.Event.ON_RESUME -> {
                    GSYVideoManager.onResume() // 全局恢复
                }
                Lifecycle.Event.ON_DESTROY -> {
                    // 注意：这里的 ON_DESTROY 是 LifecycleOwner 的，不一定是 Activity 的
                    // 更可靠的释放通常在 AndroidView 的 update 块中处理

                }
                else -> {}
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            // 释放所有播放器资源（强释放，适合在页面销毁时调用）
            GSYVideoManager.releaseAllVideos()
        }
    }
}